package cn.sumpu.app.coolsk.biz.impl.sms;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.sumpu.app.coolsk.biz.SmsBiz;
import cn.sumpu.app.coolsk.exception.AppBusinessException;
import cn.sumpu.toolkit.common.http.HttpProxy;

public class SmsBizImpl implements SmsBiz {
	private final static Logger logger = LoggerFactory
			.getLogger(SmsBizImpl.class);
	private String account;
	private String password;
	private String url;

	private final static Map<String, String> SEND_RET_MAP = new HashMap<String, String>();
	static {
		SEND_RET_MAP.put("-1", "余额不足");
		SEND_RET_MAP.put("-2", "帐户和密码错误");
		SEND_RET_MAP.put("-3", "连接服务商失败");
		SEND_RET_MAP.put("-4", "超时");
		SEND_RET_MAP.put("-5", "其他错误");
		SEND_RET_MAP.put("-6", "短信内容为空");
		SEND_RET_MAP.put("-7", "目标号码为空");
		SEND_RET_MAP.put("-8", "用户通道设置不对，应该设置三个通道");
		SEND_RET_MAP.put("-9", "捕获未知异常");
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	@Override
	public boolean send(String content, String mobilePhone)
			throws AppBusinessException {
		try {
			String msgText = java.net.URLEncoder.encode(content, "UTF-8");
			String ret = HttpProxy.doGet(url + "?types=send&account=" + account
					+ "&password=" + password + "&destmobile=" + mobilePhone
					+ "&msgText=" + msgText);
			ret = ret.trim();
			long taskId = Long.valueOf(ret);
			if (taskId > 0) {
				if (logger.isInfoEnabled()) {
					logger.info("Sms send success,task id : " + taskId);
				}
				return true;
			} else {
				if (logger.isErrorEnabled()) {
					logger.error("Sms send fail,err code : " + ret + "["
							+ SEND_RET_MAP.get(ret) + "]");
				}
				return false;
			}
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("Sms send fail,system crash.", e);
			}
			throw new AppBusinessException("Sms send fail.", e);
		}
	}

}
